/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jef.security.component;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.jef.core.constant.CommonConstants;
import org.jef.core.constant.SecurityConstants;
import org.jef.core.properties.BodyEncryProperties;
import org.jef.core.properties.JefProperties;
import org.jef.core.util.JefAesUtil;
import org.jef.core.util.R;
import org.jef.core.util.SpringContextHolder;
import org.jef.security.annotation.Inner;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.access.AccessDeniedException;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;

/**
 * @author lengleng
 * @date 2022-06-04
 *
 * 服务间接口不鉴权处理逻辑
 */
@Slf4j
@Aspect
@RequiredArgsConstructor
public class PigSecurityInnerAspect implements Ordered {

	private final HttpServletRequest request;

	@SneakyThrows
	@Before("@within(inner) || @annotation(inner)")
	public void before(JoinPoint point, Inner inner) {
		// 实际注入的inner实体由表达式后一个注解决定，即是方法上的@Inner注解实体，若方法上无@Inner注解，则获取类上的
		if (inner == null) {
			Class<?> clazz = point.getTarget().getClass();
			inner = AnnotationUtils.findAnnotation(clazz, Inner.class);
		}
		String header = request.getHeader(SecurityConstants.FROM);
		if (inner.value() && !StrUtil.equals(SecurityConstants.FROM_IN, header)) {
			log.warn("访问接口 {} 没有权限", point.getSignature().getName());
			throw new AccessDeniedException("Access is denied");
		}

	}

	@SneakyThrows
	@Around("@annotation(org.jef.security.annotation.Inner)")
    public Object after(ProceedingJoinPoint pjp) {
		Object result = pjp.proceed();

		// 检查响应是否为 R<T> 类型
		if (result instanceof R) {
			R r = (R) result;
			if (r.getData() instanceof String && r.isEncryption() && isEncry()) {
				dealDecrypt(r);
			}
		}

		return result;
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE + 1;
	}

	private void dealDecrypt(R r) {
		String encryptedData = (String) r.getData();
		try {
			JefProperties jefProperties = SpringContextHolder.getBean(JefProperties.class);
			BodyEncryProperties bodyEncry = jefProperties.getBodyencry();
			String decryptedJson = JefAesUtil.getInstance().decrypt(encryptedData, bodyEncry.getKey(), bodyEncry.getIv());
			ObjectMapper objectMapper = SpringUtil.getBean(ObjectMapper.class);
			Class clazz = r.getClazz();
			Object o = objectMapper.readValue(decryptedJson, clazz);
			r.setData(o);
		} catch (Exception e) {
			e.printStackTrace();
			// 处理解密异常
			r.setCode(CommonConstants.FAIL);
			r.setMsg("Failed to decrypt data");
		}
	}

	private static boolean isEncry() {
		JefProperties bean = SpringContextHolder.getBean(JefProperties.class);
		BodyEncryProperties bodyEncry = bean.getBodyencry();
		if (bodyEncry != null) {
			Boolean enable = bodyEncry.getEnabled();
			if (enable != null) {
				return enable;
			}
		}
		return false;
	}
}
